package com.awifi.demo.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: ToDo
 * @author: marin
 * @time: 2020/9/2 10:49
 */
//1.通过线程池来生成消费者
public class BIOServer {

    public static void main(String[] args) throws IOException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(6666);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("服务器启动！");

        while (true) {
            final Socket socket = serverSocket.accept();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("连接到一个客户端！！！");
                    handler(socket);
                }
            });
        }

    }

    public static void handler(Socket socket){
        System.out.println(Thread.currentThread().getName()+"=====");
        byte[] bytes = new byte[1024];
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            while (inputStream.read(bytes) != -1) {
                System.out.println(new String(bytes,0,inputStream.read(bytes)));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
